var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var MovieSchema = new Schema({
    doctor: String,
    title: String,
    language: String,
    country: String,
    summary: String,
    poster: String,
    flash: String,
    year: Number,
    catgory: {
        type: ObjectId,
        ref: 'Catgory'
    },
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    },
})

MovieSchema.pre('save', function () {
    if (this.isNew) {
        this.meta.createAt = this.meta.updateAt = Date.now()
    } else {
        this.meta.updateAt = Date.now()
    }

    next()
})

MovieSchema.statics = {
    fetch: function (cb) { // 取出数据库所有数据
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    findById: function (id, cb) { // 取出数据单条所有数据
        return this
            .findOne({ _id: id })
            .exec(cb)
    }
}

module.exports = MovieSchema